import React, { useEffect, useState } from 'react';
import { Tabs } from 'antd';
import { Window as WindowModel } from '../core/Window';
import FrameComponent from './Frame';

interface WindowProps {
  model: WindowModel;
}

/**
 * Window Component - React component for the Window core class
 */
const Window: React.FC<WindowProps> = ({ model }) => {
  // State to keep track of frames for re-rendering
  const [frameCount, setFrameCount] = useState(model.frames.length);
  const [activeFrameId, setActiveFrameId] = useState<string | null>(model.activeFrame?.id || null);
  
  // Re-render when frames change
  useEffect(() => {
    console.log('Window component: model frames =', model.frames);
    console.log('Window component: active frame =', model.activeFrame);
    
    // Set active frame ID for tab selection
    if (model.activeFrame && model.activeFrame.id !== activeFrameId) {
      setActiveFrameId(model.activeFrame.id);
    }
    
    // Set up a timer to check for frame changes
    const intervalId = setInterval(() => {
      // Check if frame count changed
      if (model.frames.length !== frameCount) {
        console.log('Frame count changed from', frameCount, 'to', model.frames.length);
        setFrameCount(model.frames.length);
      }
      
      // Check if active frame changed
      if (model.activeFrame && model.activeFrame.id !== activeFrameId) {
        console.log('Active frame changed from', activeFrameId, 'to', model.activeFrame.id);
        setActiveFrameId(model.activeFrame.id);
      } else if (!model.activeFrame && activeFrameId) {
        console.log('No active frame - resetting active frame ID');
        setActiveFrameId(null);
      }
    }, 100);
    
    // Clean up interval
    return () => clearInterval(intervalId);
  }, [model, frameCount, activeFrameId]);

  // Handle tab change
  const handleTabChange = (activeKey: string) => {
    const frame = model.frames.find(f => f.id === activeKey);
    if (frame) {
      model.setActiveFrame(frame);
      setActiveFrameId(frame.id);
      console.log('Window component: Tab changed, active frame =', frame.id);
    }
  };

  // Close a tab/frame
  const handleTabClose = (targetKey: string) => {
    const frame = model.frames.find(f => f.id === targetKey);
    if (frame) {
      model.closeFrame(frame);
      console.log('Window component: Closed frame', targetKey);
      
      // Update active frame ID after frame closure
      setActiveFrameId(model.activeFrame?.id || null);
    }
  };

  return (
    <div className="mini-xaf-window">
      {model.frames.length > 0 ? (
        <Tabs
          type="editable-card"
          onChange={handleTabChange}
          activeKey={activeFrameId || undefined}
          hideAdd
          onEdit={(targetKey, action) => {
            if (action === 'remove') {
              handleTabClose(targetKey as string);
            }
          }}
          items={model.frames.map(frame => ({
            key: frame.id,
            label: frame.title,
            children: <FrameComponent model={frame} />
          }))}
        />
      ) : (
        <div className="empty-window" style={{ padding: '20px', textAlign: 'center' }}>
          <p>Use the navigation menu to open a view</p>
        </div>
      )}    </div>
  );
};

export default Window;
